{% extends '@theme/base.html.twig' %}

{% form_theme form _self '@offers/form/theme.html.twig'  %}

{% block stylesheets %}
    {{ parent() }}

    <link rel="stylesheet" type="text/css" href="/assets/dist/vendor/trix/trix.css"/>
    <style type="text/css">
        #location-map {
            height: 25rem;
        }

        .spec-logo svg {
            width: 2.5rem;
        }
    </style>
{% endblock %}

{% block header %}
    {{ render_esi(controller('App\\Offers\\Controller\\LayoutController::headerAction', {specialization: specialization.slug})) }}
{% endblock %}

{%  block _offer_description_requirements_skills_entry_row %}
    <fieldset id="{{ form.vars.id }}">
        {{ form_widget(form) }}
        {{ form_errors(form) }}
    </fieldset>
{% endblock %}

{%  block _offer_description_requirements_skills_entry_widget %}
    <div class="row">
        <div class="col-md-4">{{ form_row(form.skill, {label: "Skill/Technology"}) }}</div>
        <div class="col-md-4">{{ form_row(form.required, {label: "Requirement"}) }}</div>
        <div class="col-md-2">{{ form_row(form.experience, {label: "Years of experience", help: "(optional)"}) }}</div>
        <div class="col-md-2 pt-4" data-remove></div>
    </div>
{% endblock %}

{% block body %}
<div class="container mt-4">
    {{ form_start(form, {attr: {id: form.vars.id ~ '-' ~ specialization.slug }}) }}
    <div class="row border-bottom">
        <div class="col-md-2">
            <h3 class="text-gray-500">Language</h3>
        </div>
        <div class="col-md-10">
            {{ form_row(form.locale, {label: false}) }}
            <p class="small">Language in which you are going to write the offer. It will let users to filter offers by language.</p>
        </div>
    </div>
    <div class="row mt-4 border-bottom">
        <div class="col-md-2">
            <h3 class="text-gray-500">Company</h3>
        </div>
        <div class="col-md-10">
            <div class="row">
                <div class="col-md-6 mb-3">
                    {{ form_row(form.company.name, {label: "Name", attr: {placeholder: "Company name"}} ) }}
                </div>
                <div class="col-md-6 mb-3">
                    {{ form_row(form.company.url, {label: "Homepage", attr:{placeholder:"Company hompate url"}}) }}
                </div>
                <div class="col-md-12">
                    {{ form_row(form.company.logo, {label: 'Logo', help: "Select File, square PNG/JPG logo on transparent or white background is the best choice."}) }}
                </div>
            </div>
            {{
                form_row(
                    form.company.description,
                    {
                        label: "Description",
                        help: "Between 20 and 2048 characters...",
                        attr: {
                            rows: 5
                        }
                    }
                )
            }}
        </div>
    </div>
    <div class="row mt-4 border-bottom">
        <div class="col-md-2">
            <h3 class="text-gray-500">Position</h3>
        </div>
        <div class="col-md-10">
            <div class="row">
                <div class="col"><a id="seniority-intern" data-seniority-level="0" class="mb-2 btn btn-block btn-outline-primary{% if form.position.seniorityLevel.vars.value == 0 %} active{% endif %}" href="#">Intern</a></div>
                <div class="col"><a id="seniority-junior" data-seniority-level="1" class="mb-2 btn btn-block btn-outline-primary{% if form.position.seniorityLevel.vars.value == 1 %} active{% endif %}" href="#">Junior</a></div>
                <div class="col"><a id="seniority-mid" data-seniority-level="2" class="mb-2 btn btn-block btn-outline-primary{% if form.position.seniorityLevel.vars.value == 2 %} active{% endif %}" href="#">Mid</a></div>
                <div class="col"><a id="seniority-senior" data-seniority-level="3" class="mb-2 btn btn-block btn-outline-primary{% if form.position.seniorityLevel.vars.value == 3 %} active{% endif %}" href="#">Senior</a></div>
                <div class="col"><a id="seniority-expert" data-seniority-level="4" class="mb-2 btn btn-block btn-outline-primary{% if form.position.seniorityLevel.vars.value == 4 %} active{% endif %}" href="#">Expert</a></div>
            </div>
            {{ form_row(form.position.seniorityLevel) }}

            {{ form_row(
                form.position.name,
                {label: "Job Title", attr:{placeholder: "Developer"},
                    help: "Don't put seniority level in Job Title, instead select it from the buttons above the field."
                })
            }}
            {{ form_row(form.contract, {label: "Job Type"}) }}
        </div>
    </div>
    <div class="row mt-4 border-bottom">
        <div class="col-md-2">
            <h3 class="text-gray-500">Salary</h3>
        </div>
        <div class="col-md-10">
            <div class="alert alert-success text-center text-dark small" role="alert">
                This section is optional but please remember that 90% of candidates prefer offers with transparent salary.
            </div>
            <div class="row">
                <div class="col-md-6">
                    <label>Salary Range</label>
                </div>
            </div>
            <div class="row">
                <div class="col-md-12">
                    <div class="row">
                        <div class="col-md-6">
                            {{ form_row(form.salary.min, {label: false, attr:{placeholder:"From"}}) }}
                        </div>
                        <div class="col-md-6">
                            {{ form_row(form.salary.max, {label: false, attr:{placeholder:"To"}}) }}
                        </div>
                    </div>
                </div>
                <div class="col-12">
                    {{ form_row(form.salary.net, {label: "Net income"}) }}
                </div>
                <div class="col-md-12">
                    <div class="row">
                        <div class="col-md-6">
                            {{ form_row(form.salary.currency, {label: 'Currency'}) }}
                        </div>
                        <div class="col-md-6">
                            {{ form_row(form.salary.period_type, {label: 'Periodicity'}) }}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="row mt-4 border-bottom">
        <div class="col-md-2">
            <h3 class="text-gray-500">Location</h3>
        </div>
        <div class="col-md-10">
            <div class="row">
                <div class="col"><a id="location-fully-remote" class="btn btn-block btn-outline-primary{% if form.location.type.vars.value == 0 %} active{% endif %}" href="#">Fully Remote</a></div>
                <div class="col"><a id="location-partially-remote" class="btn btn-block btn-outline-primary{% if form.location.type.vars.value == 1 %} active{% endif %}" href="#">Partially Remote</a></div>
                <div class="col"><a id="location-at-office" class="btn btn-block btn-outline-primary{% if form.location.type.vars.value == 2 %} active{% endif %}" href="#">At Office</a></div>
            </div>

            {{ form_row(form.location.type, {label: false, attr: {class: 'd-none'}}) }}

            <div class="row d-none" id="location-group">
                <div class="col-md-12">
                    {{ form_row(form.location.address, {label: false, placeholder: "Find address...", attr: {autocomplete: "off"}}) }}
                    {{ form_row(form.location.country) }}
                    {{ form_row(form.location.city) }}

                    <div id="location-map" class="mb-4"></div>
                </div>
                <div class="col-md-12">
                    {{ form_row(form.location.lat) }}
                    {{ form_row(form.location.lng) }}
                </div>
            </div>
        </div>
    </div>
    <div class="row mt-4 border-bottom">
        <div class="col-md-2">
            <h3 class="text-gray-500">Job Description</h3>
        </div>
        <div class="col-md-10">
            <div class="row">
                <div class="col-md-12">
                    <h6 class="text-gray-500">Requirements</h6>
                    <div
                            data-skills
                            data-description-requirements-skills data-prototype="{{ form_widget(form.description.requirements.skills.vars.prototype)|e('html_attr') }}"
                            data-widget-tags="{{ '<fieldset></fieldset>'|e }}"
                            data-widget-counter="{{ form.description.requirements.skills|length }}"
                    >
                        {% for skill in form.description.requirements.skills %}
                            {{ form_row(skill, {attr: {label: false}}) }}
                        {% endfor %}
                    </div>
                    {{ form_errors(form.description.requirements.skills) }}
                    <button data-skill-add type="button" class="btn btn-primary btn-sm mb-2 mt-2"><i class="fas fa-plus"></i> skill</button>
                </div>
                <div class="col-md-12">

                    {{
                        form_row(
                            form.description.requirements.description,
                            {
                                label: "Description",
                                help: "Between 20 and 2048 characters...",
                                attr:{
                                    rows: 5,
                                }
                            }
                        )
                    }}
                </div>
                <div class="col-md-12">
                    {{ form_row(form.description.technology_stack, {
                        label: "Technology Stack",
                        attr:{rows: 5},
                        help: "This field is optional and must have less than 2048 characters. Technology Stack is one the two most important parts of the offer for 90% of candidates. Use it to explain technologies, tools, methodologies he might expect. "
                        ~ " Try to be as descriptive as possible, explain typical workflow, share something about CI/CD processes, be creative!"
                    }) }}
                </div>
                <div class="col-md-12">
                    {{ form_row(
                        form.description.benefits,
                        {
                            label: "Benefits",
                            help: "Between 20 and 2048 characters.",
                            attr:{
                                rows: 5,
                            }
                        }
                    )
                    }}
                </div>
            </div>
        </div>
    </div>
    <div class="row mt-4 border-bottom">
        <div class="col-md-2">
            <h3 class="text-gray-500">Contact</h3>
        </div>
        <div class="col-md-10">
            <div class="row mb-4">
                <div class="col"><a id="switch-contact-recruiter" class="btn btn-block btn-outline-primary active" href="#">Recruiter</a></div>
                <div class="col"><a id="switch-contact-external-source" class="btn btn-block btn-outline-primary" href="#">External Source</a></div>
                {{ form_row(form.contact.type, {attr:{class:"d-none"}, label: false}) }}
            </div>
            <div class="row" id="contact-recruiter">
                <div class="col-md-6">
                    {{ form_row(form.contact.name, {label: "Recruiter name"}) }}
                </div>
                <div class="col-md-6">
                    {{ form_row(form.contact.email, {label: "Email address", help :"This is where candidates will send their resumes."}) }}
                </div>
                <div class="col-md-12">
                    {{ form_row(form.contact.phone, {label: "Phone number (optional)"}) }}
                </div>
            </div>
            <div class="row d-none" id="contact-external-source">
                <div class="col-md-12">
                    <div class="alert alert-warning text-center text-dark small" role="alert">
                        In order to apply the candidate will need to visit url provided below.
                    </div>
                    {{ form_row(form.contact.url, {label: "Offer url"}) }}
                </div>
            </div>
        </div>
    </div>
    <div class="row mt-4 border-bottom">
        <div class="col-md-2">
            <h3 class="text-gray-500">PDF</h3>
        </div>
        <div class="col-md-10">
            {{ form_row(form.offer_pdf, {label: 'PDF File', help: "Select file, offer in PDF must be 100% accurate with the one described above."}) }}
        </div>
    </div>
    {% block offer_social_media %}
    <div class="row mt-4 border-bottom">
        <div class="col-md-2">
            <h3 class="text-gray-500">Social Media</h3>
        </div>
        <div class="col-md-10">
            <h5 class="text-gray-500">Where should we post your job offer?</h5>
            <div class="form-group">
                <div class="form-check custom-switch">
                    <input type="checkbox" id="offer_post_at_homepage" class="custom-control-input disabled disable_save" checked disabled value="1">
                    <label class="switch-custom custom-control-label" for="offer_post_at_homepage">{{ specialization.slug|specialization_name }} specialization offers list</label>
                </div>
            </div>
            {% if specialization.facebookChannel and postOfferAtFacebookGroupEnabled %}
                {{ form_row(form.channels.facebook_group, {
                    label: "Facebook Group",
                    attr: {checked:"checked"},
                    label_attr: {class: "switch-custom"}
                }) }}
            {% else %}
                {{ form_row(form.channels.facebook_group, {
                    label: "Facebook Group",
                    label_attr: {class: "switch-custom"},
                    attr: { disabled: "disabled"},
                    help: "Features not available yet in this specialization."
                }) }}
            {% endif %}
            {% if specialization.twitterChannel and tweetAboutOfferEnabled %}
                {{ form_row(form.channels.twitter, {
                    label: "Twitter",
                    attr: {checked:"checked"},
                    label_attr: {class: "switch-custom"}
                }) }}
            {% else %}
                {{ form_row(form.channels.twitter, {
                    label: "Twitter",
                    label_attr: {class: "switch-custom"},
                    attr: { disabled: "disabled"},
                    help: "Features not available yet in this specialization."
                }) }}
            {% endif %}
            {% if postOfferAtFacebookGroupEnabled %}
                <p class="small text-muted">
                    Job offers at Facebook are posted by our <a href="{{ facebook.page_url }}" target="_blank">page</a>, not your personal account used to login.
                </p>
            {% endif %}
        </div>
    </div>
    {% endblock %}
    {% block offer_submit %}
    <div class="mt-4">
        <div class="row">
            <div class="col-md-2"></div>
            <div class="col-md-10">
                {% if throttled and extraOffersCount <= 0 %}
                    <div class="row">
                        <div class="col-md-12">
                            <div class="alert alert-success text-center small text-dark">
                                Sorry, you already added {{ throttleLimit }} offers in last {{ throttleSince.format('%d') }} days, please wait. Still have some really cool offers? <br/>
                                Email us some at <a href="mailto:{{ contact_email }}">{{ contact_email }}</a> and we might
                                grant you couple <strong>instant offers</strong>!
                            </div>
                        </div>
                    </div>
                {% endif %}
                <div class="row">
                    <div class="col-md-10">
                        {% if throttled and extraOffersCount <= 0 %}
                            {{ form_row(form.submit, {label: "Wait", attr:{disabled:disabled, class: 'btn btn-primary btn-lg btn-block'}}) }}
                        {% else %}
                            {{ form_row(form.submit, {label: "Submit", attr: {class: 'btn btn-primary btn-lg btn-block'}}) }}
                        {% endif %}
                    </div>
                    <div class="col-md-2">
                        {{ form_row(form.reset, {label: "Reset", attr: {class: 'btn btn-danger btn-lg btn-block'}}) }}
                    </div>
                </div>
                <p class="small text-muted">
                    We keep your work safe in your browser local storage, this means that if you accidentally refresh this page you won't lose your work, it's going to be loaded from the storage.
                    <strong>Your work is important for us!</strong>
                </p>
            </div>
        </div>
    </div>
    {% endblock %}
    {{ form_row(form._token, {attr: {class: 'disable_save'}}) }}
    {{ form_end(form, {'render_rest': false}) }}
</div>
{% endblock %}

{% block javascripts %}
<script type="text/javascript">
    $(window).on('beforeunload', function(){
       return 'Are you sure you want to leave?';
    });

    $(function () {
        {% if previousOfferData %}
            $.saveMyForm.clearStorage('{{ form.vars.id ~ '-' ~ specialization.slug }}');
            $("#{{ form.vars.id ~ '-' ~ specialization.slug }}").saveMyForm();
        {% endif %}

        {% if newOffer %}
            $("#{{ form.vars.id ~ '-' ~ specialization.slug }}").saveMyForm();
        {% endif %}

        $("#{{ form.vars.id ~ '-' ~ specialization.slug }}").submit(function() {
            $(window).unbind('beforeunload');
        });
    });

    {% if newOffer %}
        $('#{{ form.reset.vars.id }}').on('click', function() {
            $.saveMyForm.clearStorage('{{ form.vars.id ~ '-' ~ specialization.slug }}');
        });
    {% endif %}

    $('input[type="file"]').change(function(e){
        var fileName = e.target.files[0].name;
        $('.custom-file-label').html(fileName);
    });

    $('[data-skill-add]').on('click', function(e) {
        var list = $('[data-skills]');
        var counter = list.data('widget-counter') || list.children().length;
        var newWidget = list.attr('data-prototype');

        newWidget = newWidget.replace(/__name__/g, counter);
        counter++;
        list.data('widget-counter', counter);

        var newElem = $(list.attr('data-widget-tags')).html(newWidget);
        newElem.appendTo(list);
        addSkillFormDeleteLink($(newElem));
    });

    $('[data-skills]').find('fieldset').each(function() {
        addSkillFormDeleteLink($(this));
    });

    function addSkillFormDeleteLink($skillElement) {
        var $removeFormButton = $('<button type="button" class="btn btn-secondary btn-sm mt-2"><i class="fas fa-minus-circle"></i> delete</button>');
        $skillElement.find('[data-remove]').append($removeFormButton);

        $removeFormButton.on('click', function(e) {
            // remove the li for the tag form
            $skillElement.remove();
        });
    }

    function changeSeniority(value, element) {
        $('[data-seniority-level]').removeClass('active');
        $('#{{ form.position.seniorityLevel.vars.id }}').val(value);
        $('#{{ form.position.seniorityLevel.vars.id }}').change();
        $(element).addClass('active');
    }

    function setActiveSeniority(element) {
        $('[data-seniority-level]').removeClass('active');
        $(element).addClass('active');
    }

    $('[data-seniority-level]').click(function (e) {
        e.preventDefault();

        changeSeniority(parseInt($(this).data('seniority-level'), 10), e.currentTarget);
    });

    $('#{{ form.position.seniorityLevel.vars.id }}').on('change', function(e) {
        console.log();
        switch ($(this).val()) {
            case 0:
                setActiveSeniority('#seniority-intern');
                break;
            case 1:
                setActiveSeniority('#seniority-junior');
                break;
            case 2:
                setActiveSeniority('#seniority-mid');
                break;
            case 3:
                setActiveSeniority('#seniority-senior');
                break;
            case 4:
                setActiveSeniority('#seniority-expert');
                break;
        }
    });

    function fullyRemote() {
        $('#location-fully-remote').addClass('active');
        $('#location-partially-remote').removeClass('active');
        $('#location-at-office').removeClass('active');
        $('#{{ form.location.type.vars.id }}_0').prop('checked', true);
        $('#{{ form.location.type.vars.id }}_1').prop('checked', false);
        $('#{{ form.location.type.vars.id }}_2').prop('checked', false);
        $('#location-group').addClass('d-none');
    }

    function partiallyRemote() {
        $('#location-fully-remote').removeClass('active');
        $('#location-partially-remote').addClass('active');
        $('#location-at-office').removeClass('active');
        $('#{{ form.location.type.vars.id }}_0').prop('checked', false);
        $('#{{ form.location.type.vars.id }}_1').prop('checked', true);
        $('#{{ form.location.type.vars.id }}_2').prop('checked', false);
        $('#location-group').removeClass('d-none');
    }

    function atOffice() {
        $('#location-fully-remote').removeClass('active');
        $('#location-partially-remote').removeClass('active');
        $('#location-at-office').addClass('active');
        $('#{{ form.location.type.vars.id }}_0').prop('checked', false);
        $('#{{ form.location.type.vars.id }}_1').prop('checked', false);
        $('#{{ form.location.type.vars.id }}_2').prop('checked', true);
        $('#location-group').removeClass('d-none');
    }

    $('#location-fully-remote').click((e => {
        e.preventDefault();

        $('#{{ form.location.type.vars.id }}_0').change();
        fullyRemote();
    }));
    $('#location-partially-remote').click((e => {
        e.preventDefault();

        $('#{{ form.location.type.vars.id }}_1').change();
        partiallyRemote();
    }));
    $('#location-at-office').click((e => {
        e.preventDefault();

        $('#{{ form.location.type.vars.id }}_2').change();
        atOffice();
    }));

    {% if form.location.type.vars.value == 0 %}
    fullyRemote();
    {% elseif form.location.type.vars.value == 1 %}
    partiallyRemote();
    {% else %}
    atOffice();
    {% endif %}

    $('#{{ form.location.type.vars.id }}_0').on('change', function() {
        fullyRemote();
    });
    $('#{{ form.location.type.vars.id }}_1').on('change', function() {
        partiallyRemote();
    });
    $('#{{ form.location.type.vars.id }}_2').on('change', function() {
        atOffice();
    });

    function contactRecruiter() {
        $('#switch-contact-recruiter').addClass('active');
        $('#switch-contact-external-source').removeClass('active');
        $('#{{ form.contact.type.vars.id }}_0').prop('checked', true);
        $('#{{ form.contact.type.vars.id }}_1').prop('checked', false);

        $('#contact-recruiter').removeClass('d-none');
        $('#contact-external-source').addClass('d-none');
    }

    function contactExternalSource() {
        $('#switch-contact-recruiter').removeClass('active');
        $('#switch-contact-external-source').addClass('active');
        $('#{{ form.contact.type.vars.id }}_0').prop('checked', false);
        $('#{{ form.contact.type.vars.id }}_1').prop('checked', true);

        $('#contact-recruiter').addClass('d-none');
        $('#contact-external-source').removeClass('d-none');
    }

    $('#switch-contact-recruiter').click((e => {
        e.preventDefault();
        contactRecruiter();
    }));

    $('#switch-contact-external-source').click((e => {
        e.preventDefault();

        contactExternalSource();
    }));

    {% if form.contact.type.vars.value == 0 %}
        contactRecruiter();
    {% else %}
        contactExternalSource();
    {% endif %}

    $('#{{ form.contact.type.vars.id }}_0').on('change', function() {
        contactRecruiter();
    });
    $('#{{ form.location.type.vars.id }}_1').on('change', function() {
        contactExternalSource();
    });

    function initMap() {
        var map = new google.maps.Map(document.getElementById('location-map'), {
            zoom: 14,
            center: {
                lat: $('#{{ form.location.lat.vars.id }}').val() ? parseFloat($('#{{ form.location.lat.vars.id }}').val()) : 50.06212,
                lng: $('#{{ form.location.lng.vars.id }}').val() ? parseFloat($('#{{ form.location.lng.vars.id }}').val()) : 19.9353153
            }
        });
        var geocoder = new google.maps.Geocoder;

        let searchInput = document.getElementById('{{ form.location.address.vars.id }}');
        let countryInput = document.getElementById('{{ form.location.country.vars.id }}');
        let cityInput = document.getElementById('{{ form.location.city.vars.id }}');

        var autocomplete = new google.maps.places.Autocomplete(searchInput);

        if ($('#{{ form.location.lat.vars.id }}').val() && $('#{{ form.location.lng.vars.id }}').val()) {
            var marker = new google.maps.Marker({
                map: map,
                center: {
                    lat: parseFloat($('#{{ form.location.lat.vars.id }}').val()),
                    lng: parseFloat($('#{{ form.location.lng.vars.id }}').val()),
                },
                position: {
                    lat: parseFloat($('#{{ form.location.lat.vars.id }}').val()),
                    lng: parseFloat($('#{{ form.location.lng.vars.id }}').val()),
                }
            });
        } else {
            var marker = new google.maps.Marker({
                map: map,
                center: {
                    lat: 50.06212,
                    lng: 19.9353153
                },
            });
        }

        marker.addListener('position_changed', function(e) {
            $('#{{ form.location.lat.vars.id }}').val(this.getPosition().lat()).change();
            $('#{{ form.location.lng.vars.id }}').val(this.getPosition().lng()).change();
        });

        function geocode(location) {
            geocoder.geocode(
                {'location' : location},
                function (results, status) {
                    if (status === 'OK') {
                        if (results[0]) {
                            searchInput.value = results[0].formatted_address;

                            countryInput.value = Array.from(results[0].address_components)
                                .find(component => component.types[0] === 'country' && component.types[1] === "political")['short_name'];

                            let city = false;

                            if (!city) {
                                city = Array.from(results[0].address_components).find(component => component.types.includes('locality') && component.types.includes("political"));
                            }
                            if (!city) {
                                city = Array.from(results[0].address_components).find(component => component.types.includes('sublocality') && component.types.includes("political"));
                            }
                            if (!city) {
                                city = Array.from(results[0].address_components).find(component => component.types.includes('administrative_area_level_3') && component.types.includes("political"));
                            }
                            if (!city) {
                                city = Array.from(results[0].address_components).find(component => component.types.includes('administrative_area_level_2') && component.types.includes("political"));
                            }
                            if (!city) {
                                city = Array.from(results[0].address_components).find(component => component.types.includes('administrative_area_level_1') && component.types.includes("political"));
                            }

                            cityInput.value = city ? city['short_name'] : '';
                        }
                    }
                }
            );
        }

        if ($('#{{ form.location.lat.vars.id }}').val() && $('#{{ form.location.lng.vars.id }}').val()) {
            geocode({lat: parseFloat($('#{{ form.location.lat.vars.id }}').val()), lng: parseFloat($('#{{ form.location.lng.vars.id }}').val())});
        }

        map.addListener('click', function(e) {
            marker.setPosition(e.latLng);
            marker.setVisible(true);

            geocode(e.latLng);

            map.panTo(e.latLng);
        });

        autocomplete.bindTo('bounds', map);

        autocomplete.addListener('place_changed', function() {
            var place = autocomplete.getPlace();
            if (!place.geometry) {
                searchInput.value = "";
                document.getElementById('{{ form.location.lat.vars.id }}').value = "";
                document.getElementById('{{ form.location.lng.vars.id }}').value = "";

                return;
            }

            countryInput.value = Array.from(place.address_components)
                .find(component => component.types[0] === 'country' && component.types[1] === "political")['short_name'];

            let city = false;

            if (!city) {
                city = Array.from(place.address_components).find(component => component.types.includes('locality') && component.types.includes("political"));
            }
            if (!city) {
                city = Array.from(place.address_components).find(component => component.types.includes('sublocality') && component.types.includes("political"));
            }
            if (!city) {
                city = Array.from(place.address_components).find(component => component.types.includes('administrative_area_level_3') && component.types.includes("political"));
            }
            if (!city) {
                city = Array.from(place.address_components).find(component => component.types.includes('administrative_area_level_2') && component.types.includes("political"));
            }
            if (!city) {
                city = Array.from(place.address_components).find(component => component.types.includes('administrative_area_level_1') && component.types.includes("political"));
            }

            cityInput.value = city ? city['short_name'] : '';

            marker.setPosition(place.geometry.location);
            map.panTo(place.geometry.location);
            marker.setVisible(true);
        });

        searchInput.addEventListener('keypress', (event) => {
            if (event.keyCode === 13) {
                event.preventDefault();
                event.stopPropagation();
            }
        });
    }
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key={{ google.maps.key }}&libraries=places&&callback=initMap"></script>
{% endblock %}